package com.own.component.elastic.service.config;

import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import co.elastic.clients.util.ObjectBuilder;
import lombok.Builder;

import java.util.function.Function;

/**
 * ElasticSearchHighlightHandler
 *
 * @author chenxueli
 * @date 2023-11-21 11:47:00
 */
@Builder
public class ElasticSearchHighlightHandler {

    /**
     * 默认高亮字段
     */
    private String[] fields;
    /**
     * 高亮信息前缀
     */
    @Builder.Default
    private String preTags = "<em style='color:red'>";
    /**
     * 高亮信息后缀
     */
    @Builder.Default
    private String postTags = "</em>";

    /**
     * 初始化的方法
     *
     * @return 初始化的方法
     */
    public Function<Highlight.Builder, ObjectBuilder<Highlight>> init() {
        if (fields == null || fields.length == 0) {
            return null;
        }
        return builder -> {
            for (var field : fields) {
                builder = builder.fields(
                        field,
                        HighlightField.of(h -> h.requireFieldMatch(false).preTags(preTags).postTags(postTags))
                );
            }
            return builder;
        };
    }

}
